<template>
	<view class="contentBlue">
		<view class="padding-top" :class="getContentClass">
			<view class="text-sm text-white flex align-center justify-center padding-bottom">
				<view class="flex align-end">
					<text v-if="deviceNormal" class="cuIcon-title text-blue"></text>
					<text v-if="deviceLowAlarm" class="cuIcon-title text-yellow"></text>
					<text v-if="deviceGuZhang" class="cuIcon-title text-yellow"></text>
					<text v-if="deviceHightAlarm" class="cuIcon-title text-red"></text>
					<text v-if="deviceOffline" class="cuIcon-title text-gray"></text>
					<text class="margin-left-xs">{{ deviceOffline ? '离线' : '在线' }}</text>
				</view>
				<view class="margin-left-sm margin-right-xs">|</view>
				<view class="margin-left-xs">
					<image class="cu-avatar xs" style="background-color: transparent" v-if="deviceOffline" src="@/static/images/off_line.png"></image>
					<image class="cu-avatar xs" style="background-color: transparent" v-if="!deviceOffline" src="@/static/images/on_line.gif"></image>
				</view>
			</view>
			<ripple-gray v-if="deviceOffline" />
			<ripple-red v-if="deviceHightAlarm" :value="mqttvalue" :valueUnit="mqttvalueUnit" />
			<ripple-yellow v-if="deviceLowAlarm" :value="mqttvalue" :valueUnit="mqttvalueUnit" />
			<ripple-guzhang v-if="deviceGuZhang" :value="mqttvalue" :valueUnit="mqttvalueUnit" />
			<ripple-blue v-if="deviceNormal"></ripple-blue>
			<view class="top-content" v-if="deviceOffline">
				<text class="text-sm text-white">目前设备已离线</text>
			</view>
			<view class="top-content" v-else-if="deviceNormal">
				<text class="text-sm text-white">目前暂未检测到异常情况</text>
			</view>
			<view class="top-content" v-else-if="deviceGuZhang">
				<text class="text-sm text-white">{{ getDictObjLabel('alarm_type', newMQTTData.level) }}</text>
			</view>
			<view class="top-content" v-else>
				<text class="text-sm text-white">{{ name }}</text>
				<text class="text-sm text-white">报警时间:{{ time }}</text>
			</view>
			<view class="policeInfoContent" @click="goToPoliceRecord">
				<view class="policeInfoContent-title">
					<view class="policeInfoContentLeftContent">
						<view class="tip-blue"></view>
						<text class="text-df">今日报警信息</text>
					</view>
					<uni-badge class="uni-badge-left-margin" :text="todayAlertsCount" />
				</view>

				<view class="police-info-list-content">
					<view class="police-info-list" :key="index" v-for="(item, index) in todayAlertsList">
						<view class="tip-blue-cicle"></view>
						<view class="tip-blue-line"></view>
						<view class="desc text-sm">
							{{ dateFomatterHHmmss(item.ts) }}
							{{ item.slaveName }}浓度发生{{ levelDes(item) }}报警,浓度{{ item.data }}{{ item.propertyUnit }}
						</view>
					</view>
				</view>
			</view>
			<view class="buildContent" @click="goToBuildingDetail">
				<view class="buildContent-info">
					<view class="buildContent-info-bar">
						<view class="buildContent-info-tip-maker"></view>
						<text class="text-df">建筑物</text>
					</view>
					<view class="buildContent-info-info">
						<view class="flexrowcenter margin-top-xs">
							<image class="normalLineicon" src="@/static/images/common/police-building.png" />
							<text class="text-sm text-black">{{ buildingName }}</text>
						</view>
						<view class="flexrowcenter margin-top-xs">
							<image class="normalLineicon" src="@/static/images/common/police-build-address.png" />
							<text class="text-xs text-black">{{ address }}</text>
						</view>
					</view>
				</view>

				<view style="flex: 1; display: flex; flex-direction: row; justify-content: flex-end; margin-right: 10rpx">
					<image style="height: 200rpx; width: 200rpx" :src="getMapUrl"></image>
				</view>
			</view>
			<!-- <map :latitude="40.7128" :longitude="74.0060" :scale="11"></map> -->
			<view class="detector bgcolorfff">
				<view class="flexrowcenter bgcolorfff">
					<view class="tip-blue"></view>
					<view>探测器</view>
				</view>
				<view class="flexrow wrap-content" v-if="deviceData">
					<view class="detectoritem shadow-warp padding-xs" @click="gotoDetectorDetails(item)" v-for="(item, index) in deviceData">
						<view class="title-detectoritem-content">
							<text class="text-sm">{{ item.slaveName }}</text>
							<view class="imageLineStatusSmall">
								<image class="imageLineStatusSmall" v-if="deviceOffline" src="@/static/images/common/signal-offline.png"></image>
								<image class="imageLineStatusSmall" v-else src="@/static/images/common/signal-online.png"></image>
							</view>
						</view>
						<view class="flexrow">
							<image class="detectoritem-content-image" :src="getImageUrl(item.productImg)"></image>
							<view class="detectoritem-rightinfo">
								<view class="flexrowcenter" v-if="item.data != undefined">
									<template v-if="[0, 1, 2].includes(item.level)">
										<text class="text-sm" :class="getTextClass(item.level)">{{ item.data }}</text>
										<text class="text-sm" :class="getTextClass(item.level)">{{ item.propertyUnit }}</text>
									</template>
									<text v-if="item.level == 1" class="text-xs height-color-text-tip margin-left-xs">高报</text>
									<text v-else-if="item.level == 2" class="text-xs low-color-text-tip margin-left-xs">低报</text>
									<text v-else-if="item.level == 0" class="text-xs low-color-text-tip margin-left-xs" style="color: black; background-color: #fff">
										{{ getDictObjLabel('alarm_type', item.level) }}
									</text>
									<text v-else class="text-xs low-color-text-tip margin-left-xs">{{ getDictObjLabel('alarm_type', item.level) }}</text>
								</view>
								<text class="text-sm margin-top-sm" v-if="item.propertyName != undefined">{{ item.propertyName }}</text>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { getDeviceDetail } from '@/api/devices';
import config from '@/config';
const imageUrl = config.imageUrl;
import dayjs from 'dayjs';
import MQTT from '../../../utils/mqtt';
import { getDictObj } from '@/utils/dict';
export default {
	data() {
		return {
			dictMap: this.$store.state.dict.dictMap,
			name: '',
			time: '',
			buildingId: '',
			buildingName: '',
			address: '',
			deviceName: '',
			lon: '',
			lat: '',
			deviceData: null,
			deviceId: null,
			todayAlertsList: [],
			todayAlertsCount: 0,
			mqttvalue: '',
			mqttvalueUnit: '',
			deviceOffline: false,
			deviceHightAlarm: false,
			deviceLowAlarm: false,
			deviceNormal: true,
			deviceGuZhang: false,
			newMQTTData: {},
			lineStatus: null
		};
	},
	computed: {
		getMapUrl() {
			const url = `https://restapi.amap.com/v3/staticmap?markers=mid,0xFF0000,A:${this.lon},${this.lat}&key=1d56699d521360dfe93d513fefbf5b93`;
			return url;
		},
		getBgColor() {
			if (this.deviceOffline) {
				return '#2e3d52';
			}
			if (this.deviceHightAlarm) {
				return '#ff4646';
			}
			if (this.deviceLowAlarm) {
				return '#f1a25d';
			}
			if (this.deviceGuZhang) {
				return '#f1a25d';
			}
			if (this.deviceNormal) {
				return '#4487f6';
			}
		},
		getContentClass() {
			if (this.deviceOffline) {
				return 'contentGray';
			}
			if (this.deviceHightAlarm) {
				return 'contentRed';
			}
			if (this.deviceLowAlarm) {
				return 'contentYellow';
			}
			if (this.deviceGuZhang) {
				return 'contentYellow';
			}
			if (this.deviceNormal) {
				return 'contentBlue';
			}
		}
	},
	filter: {},
	onLoad(query) {
		this.deviceId = query.deviceId;
	},
	onShow() {
		this.init();
	},
	onUnload() {
		this.mqttUnListen();
	},
	onNavigationBarButtonTap() {
		uni.navigateTo({
			url: '/pages/devices/detailparam/index?deviceId=' + this.deviceId
		});
	},
	methods: {
		getDictObjLabel(dictObj, value) {
			const dict = getDictObj(dictObj, value);
			return dict ? dict.label : '';
		},
		goToBuildingDetail() {
			this.$tab.navigateTo('/pages/mine/building/CreateOrEditBuilding?id=' + this.buildingId);
		},
		init() {
			getDeviceDetail({ deviceId: this.deviceId }).then((res) => {
				const data = res.data; // 读取 data 数据
				const buildingDeviceInfo = data.buildingDeviceInfo || {};
				this.buildingId = buildingDeviceInfo.buildingId;
				this.buildingName = buildingDeviceInfo.buildingName;
				this.deviceName = buildingDeviceInfo.deviceName;
				this.address = buildingDeviceInfo.address;
				this.lon = buildingDeviceInfo.coordinate.split(',')[0]; //经度
				this.lat = buildingDeviceInfo.coordinate.split(',')[1]; //纬度
				this.lineStatus = buildingDeviceInfo.lineStatus;
				this.deviceData = data.deviceData || [];
				const todayAlertsListArray = data.todayAlertsList || [];
				const todayAlertsList = todayAlertsListArray.slice(0, 3);
				this.todayAlertsList = todayAlertsList;
				this.todayAlertsCount = data.todayAlertsCount || 0;
				if (buildingDeviceInfo.lineStatus == 0) {
					this.setOfflineAlarm();
				}
				this.setBarTitle(this.deviceName);
				console.log('11111111111', res);
				this.getDeviceData(res.data.deviceData);
				// mqtt
				this.mqttListen();
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: this.getBgColor,
					success() {
						console.log('setNavigationBarColor success');
					}
				});
			});
		},
		getTextClass(level) {
			if (level == 2) {
				return 'low-color-text';
			}
			if (level == 1) {
				return 'height-color-text';
			}
		},
		getTextTipClass(level) {
			if (level == 2) {
				return 'height-color-text-tip';
			}
			if (level == 1) {
				return 'low-color-text-tip';
			}
		},
		dateFomatterYYYYMMDD(date) {
			return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '';
		},
		setNormal() {
			this.deviceOffline = false;
			this.deviceHightAlarm = false;
			this.deviceLowAlarm = false;
			this.deviceGuZhang = false;
			this.deviceNormal = true;
		},
		setHightAlarm() {
			this.deviceOffline = false;
			this.deviceHightAlarm = true;
			this.deviceLowAlarm = false;
			this.deviceGuZhang = false;
			this.deviceNormal = false;
		},
		setLowAlarm() {
			this.deviceOffline = false;
			this.deviceHightAlarm = false;
			this.deviceLowAlarm = true;
			this.deviceGuZhang = false;
			this.deviceNormal = false;
		},
		setGuZhang() {
			// console.log('setGuZhang');
			this.deviceOffline = false;
			this.deviceHightAlarm = false;
			this.deviceLowAlarm = false;
			this.deviceGuZhang = true;
			this.deviceNormal = false;
		},
		setOfflineAlarm() {
			this.deviceOffline = true;
			this.deviceHightAlarm = false;
			this.deviceLowAlarm = false;
			this.deviceNormal = false;
			this.deviceGuZhang = false;
		},
		getDeviceData(data) {
			console.log(data, 'data');
			const leavelData = data.filter((item) => item.level !== 0);
			console.log(leavelData, 'leavelData');
			if (leavelData.length > 0) {
				// 获取最新的记录
				const latestRecord = leavelData.reduce((latest, current) => {
					return new Date(current.ts) > new Date(latest.ts) ? current : latest;
				});
				this.newMQTTData = latestRecord;
				this.setDeviceType(latestRecord);
			} else if (leavelData.length === 0) {
				// 获取最新的记录
				const latestRecord = data.reduce((latest, current) => {
					return new Date(current.ts) > new Date(latest.ts) ? current : latest;
				});
				this.newMQTTData = latestRecord;
				this.setDeviceType(latestRecord);
				console.log(latestRecord, 'latestRecord');
			}
		},
		setDeviceType(mqttData) {
			// console.log(mqttData, 'mqttData222')
			if (this.lineStatus === 1) {
				this.mqttvalue = mqttData.data;
				this.mqttvalueUnit = mqttData.unit;
				switch (mqttData.level) {
					case 0:
						this.setNormal();
						break;
					case 1:
						this.setHightAlarm();
						this.name = mqttData.slaveName + '发生' + mqttData.propertyName + '气体；浓度值' + mqttData.data + mqttData.propertyUnit;
						this.time = this.dateFomatterYYYYMMDD(mqttData.ts);
						break;
					case 2:
						this.setLowAlarm();
						this.name = mqttData.slaveName + '发生' + mqttData.propertyName + '气体；浓度值' + mqttData.data + mqttData.propertyUnit;
						this.time = this.dateFomatterYYYYMMDD(mqttData.ts);
						break;
					case 21:
						this.setOfflineAlarm();
						this.name = mqttData.slaveName + '已离线';
						this.time = this.dateFomatterYYYYMMDD(mqttData.ts);
						break;
					case 3:
					case 4:
					case 5:
					case 6:
					case 7:
					case 8:
						this.setGuZhang();
						this.name = mqttData.slaveName + '发生' + mqttData.propertyName + '气体';
						this.time = this.dateFomatterYYYYMMDD(mqttData.ts);
						break;
					default:
						this.setNormal();
				}
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: this.getBgColor,
					success() {
						console.log('setNavigationBarColor success');
					}
				});
			} else if (this.lineStatus === 0) {
				this.setOfflineAlarm();
				this.name = mqttData.slaveName + '已离线';
				this.time = this.dateFomatterYYYYMMDD(mqttData.ts);
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: this.getBgColor,
					success() {
						console.log('setNavigationBarColor success');
					}
				});
			}
		},
		mqttListen() {
			const deviceId = this.deviceId;
			const that = this;
			let it = MQTT.getInstance();
			const topic = `device/${deviceId}/property/post`;
			// console.log(topic, 'topic')
			it.subscribe(topic, 0);
			it.set_message_callback(topic, (topic, payload) => {
				const mqttData = JSON.parse(payload.toString());
				// console.log(mqttData, 'mqttData')
				this.newMQTTData = mqttData;
				this.mqttvalue = mqttData.data;
				this.mqttvalueUnit = mqttData.unit;
				this.deviceData.forEach((item, index) => {
					if (item.slaveId === mqttData.slaveId) {
						this.deviceData[index].level = mqttData.level;
						this.deviceData[index].data = mqttData.data;
					}
				});
				this.setDeviceType(mqttData);
				uni.setNavigationBarColor({
					frontColor: '#ffffff',
					backgroundColor: that.getBgColor,
					success() {
						console.log('setNavigationBarColor success');
					}
				});
			});
		},
		mqttUnListen() {
			const deviceId = this.deviceId;
			let it = MQTT.getInstance();
			const topic = `device/${deviceId}/property/post`;
			it.unsubscribe(topic, 0);
		},
		setBarTitle(title) {
			uni.setNavigationBarTitle({
				title: title
			});
		},
		getImageUrl(url) {
			return imageUrl + url;
		},
		dateFomatterHHmmss(date) {
			return date ? dayjs(date).format('HH:mm:ss') : '';
		},
		levelDes(item) {
			let level = item.level;
			let label = '';
			const alarm_type = this.dictMap?.alarm_type || [];
			alarm_type.map((item) => {
				if (item.value == level) {
					label = item.label;
				}
			});
			return label;
		},
		gotoDetectorDetails(data) {
			uni.navigateTo({
				url:
					'/pages/devices/detector/detector?deviceId=' +
					data.deviceId +
					'&slaveId=' +
					data.slaveId +
					'&slaveName=' +
					data.slaveName +
					'&propertyName=' +
					data.propertyName
			});
			uni.$once('refresh-detector', () => {
				this.init();
			});
		},
		goToPoliceRecord() {
			uni.navigateTo({
				url: '/pages/police/police-record/police-record?deviceId=' + this.deviceId
			});
		}
	}
};
</script>

<style scoped lang="scss">
.contentRed {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-bottom: calc(var(--window-bottom) + 20px);
	background-image: linear-gradient(to bottom, #ff4646, #fff);
}
.contentBlue {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-bottom: calc(var(--window-bottom) + 20px);
	background-image: linear-gradient(to bottom, #4487f6, #fff);
}
.contentGray {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-bottom: calc(var(--window-bottom) + 20px);
	background-image: linear-gradient(to bottom, #2e3d52, #fff);
}

.contentYellow {
	display: flex;
	flex-direction: column;
	height: 100%;
	padding-bottom: calc(var(--window-bottom) + 20px);
	background-image: linear-gradient(to bottom, #f1a25d, #fff);
}

.policeInfoContent-title {
	display: flex;
	flex-direction: flex;
	justify-content: space-between;
	padding-left: 10rpx;
	padding-right: 10rpx;
	padding-top: 10rpx;
	margin-bottom: 10rpx;
}

.policeInfoContent {
	display: flex;
	flex-direction: column;
	background-color: #fff;
	width: 730rpx;
	height: 240rpx;
	border-radius: 2rpx;
	margin-top: 20rpx;
	margin-left: 10rpx;
	margin-right: 10rpx;
}
.normalLineicon {
	/*margin-left: 5px;*/
	/*margin-right: 5px;*/
	width: 18px;
	height: 18px;
	margin-right: 2px;
}

.policeInfoContentLeftContent {
	align-items: center;
	font-size: 20rpx;
	color: #333333;
	display: flex;
	flex-direction: row;
}

.top-content {
	margin-top: 20rpx;
	display: flex;
	flex-direction: column;
	color: #fff;
	align-items: center;
}
.wrap-content {
	flex-wrap: wrap;
	padding: 30rpx;
}
.tip-blue {
	margin-left: 10rpx;
	margin-right: 10rpx;
	height: 24rpx;
	width: 6rpx;
	border-radius: 2rpx;
	background-color: #1654ff;
}
.police-info-list {
	display: flex;
	flex-direction: row;
	align-items: center;
	margin-left: 60rpx;
	margin-top: 10rpx;
	opacity: 1;
	height: 40rpx;
	transition: opacity 0s linear;
	.tip-blue-cicle {
		margin-left: 10rpx;
		height: 12rpx;
		width: 12rpx;
		border-radius: 6rpx;
		background-color: #1654ff;
	}
	.tip-blue-line {
		height: 2rpx;
		width: 40rpx;
		margin-left: 10rpx;
		margin-right: 10rpx;
		border-radius: 1rpx;
		background-color: #1654ff;
	}
	.desc {
		font-size: #1654ff;
	}
}

.police-info-list-content > :nth-child(1) {
	opacity: 1;
}

.police-info-list-content > :nth-child(2) {
	opacity: 0.6;
}

.police-info-list-content > :nth-child(3) {
	opacity: 0.2;
}

.buildContent {
	display: flex;
	height: 200rpx;
	margin-top: 18rpx;
	margin-left: 10rpx;
	margin-right: 10rpx;
	flex-direction: row;
	background-color: #fff;
}

.buildContent-info {
	max-width: 320rpx;
	margin-top: 10rpx;
	margin-left: 14rpx;
	display: flex;
	flex-direction: column;
}

.buildContent-info-bar {
	display: flex;
	flex-direction: row;
	align-items: center;
}

.buildContent-info-info {
	display: flex;
	flex-direction: column;
}

.buildContent-info-tip-maker {
	margin-right: 10rpx;
	height: 24rpx;
	width: 6rpx;
	border-radius: 2rpx;
	background-color: #1654ff;
}

.buildContent-map {
	flex: 1;
}

.detectoritemContent {
	display: flex;
	flex-direction: row;
	flex-wrap: wrap;
	background-color: #f5f6f7;
	flex: 1;
	width: 100%;
	padding-left: 10rpx;
	padding-right: 10rpx;
}

.detector {
	min-height: 200rpx;
	margin-top: 20rpx;
	margin-left: 10rpx;
	margin-right: 10rpx;
	border-radius: 4rpx;
	padding-top: 12rpx;
}

.detectoritem {
	/*margin-top: 20rpx;*/
	margin-bottom: 20rpx;
	border-color: black;
	border-width: 2rpx;
	display: flex;
	background-color: #fff;
	flex-direction: column;
	width: 310rpx;
	border-radius: 4rpx;
	height: 160rpx;
	margin-right: 20rpx;
}

.title-detectoritem-content {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
	height: 50rpx;
	width: 300rpx;
}

.detectoritem-content-image {
	width: 100rpx;
	height: 100rpx;
}
.imageLineStatusSmall {
	width: 14px;
	height: 14px;
}
.detectoritem-rightinfo {
	display: flex;
	justify-content: center;
	flex-direction: column;
	flex: 1;
	align-items: center;
	font-size: 12px;
}

page {
	height: 100%;
}
</style>
